import {
  DeleteOutlined,
  EditOutlined,
  PlusCircleOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { Button, Flex, Space, Table, Tag, Tooltip } from 'antd';
import { SPACE } from '@/constants/themeConstant.js';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import ModalUtil from '@/utils/modal.js';
import { TableView } from './styles.jsx';
import { LIMIT } from '@/constants/pageConstant.js';

/**
 * 表格组件
 *
 * @param {Object} props 组件属性
 * @param {String} props.title 表格标题
 * @param {Array} props.columns 表格列配置
 * @param {Array} props.dataList 表格数据
 * @param {Function} props.request 表格请求函数
 * @param {Function} props.onRowEdit 行编辑事件
 * @param {Function} props.onRowDelete 行删除事件
 * @param {Function} props.onEdit 编辑事件
 * @param {Function} props.onAdd 新增事件
 * @param {Function} props.onDelete 删除事件
 * @param {Function} props.rowEditDisabled 行编辑禁用函数
 * @param {Function} props.rowDeleteDisabled 行删除禁用函数
 * @param {Function} props.addDisabled 新增禁用函数
 * @param {Function} props.deleteDisabled 删除禁用函数
 * @param {Object} props.rowSelection 行选择配置
 * @param {String} props.rowKey 行主键
 * @param {Boolean} props.bordered 边框
 * @param {Number} props.optionsWidth 操作列宽度
 * @param {ReactNode} props.children 表格子组件
 * @param {ReactNode} props.toolbar 工具栏组件
 * @param {Object} props.pagination 表格分页配置
 * @param {Function} props.getOptions 更多操作
 * @param {Function} props.hideDelete 隐藏删除按钮
 * @param {Function} props.hideEdit 隐藏编辑按钮
 * @param {Object} props.scroll 表格滚动配置
 */
export const CustomTable = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    request: () => {
      defaultRequest();
    },
    selectedRows,
    setSelectedRows,
    setPageNo
  }));

  const sizeType = props?.size || 'small';

  const [total, setTotal] = useState(0);
  const [dataList, setDataList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pageSize, setPageSize] = useState(LIMIT);
  const [pageNo, setPageNo] = useState(1);
  const [selectedRows, setSelectedRows] = useState([]);

  // 分页配置
  const paginationConfig = {
    position: ['bottomRight'],
    pageSize: pageSize,
    current: pageNo,
    total: total,
    showQuickJumper: true,
    hideOnSinglePage: true,
    showTotal: (total, range) => {
      return `当前页 ${range[0]}-${range[1]}条/共 ${total} 条`;
    },
    pageSizeOptions: [`${pageSize}`, `${pageSize * 2}`, `${pageSize * 5}`, `${pageSize * 10}`]
  };

  useEffect(() => {
    defaultRequest();
  }, []);

  /**
   * 携带默认参数请求
   */
  const defaultRequest = () => {
    request({
      pagination: paginationConfig
    });
  };

  /**
   * 网络数据请求
   *
   * @param {Object} options 请求参数
   * @param {Object} options.page 分页参数
   * @param callback 回调函数 (可选)
   */
  const request = (options, callback) => {
    if (props?.request) {
      setLoading(true);
      props
        .request(options)
        .then(({ data, success, total }) => {
          if (success) {
            setDataList(data);
            setTotal(total || 0);
          }
          setLoading(false);
          callback?.();
        })
        .catch(() => {
          setLoading(false);
        });
    }
  };

  const getOptions = (row) => {
    let options = [];
    if (props?.onRowEdit && props?.hideEdit?.(row) !== true) {
      options.push(
        <Button
          key="edit-operation"
          type="primary"
          disabled={props?.editDisabled || props?.rowEditDisabled?.(row)}
          onClick={() => props?.onRowEdit?.(row)}
          size={sizeType}
        >
          编辑
        </Button>
      );
    }
    if (props?.onRowDelete && props?.hideDelete?.(row) !== true) {
      options.push(
        <Button
          key="delete-operation"
          type="primary"
          disabled={props?.deleteDisabled || props?.rowDeleteDisabled?.(row)}
          danger
          onClick={() => props?.onRowDelete?.(row)}
          size={sizeType}
        >
          删除
        </Button>
      );
    }
    if (props?.getOptions) {
      options = [...options, ...props.getOptions(row)];
    }
    return [<Space key="operations">{options}</Space>];
  };

  function getColumns() {
    const columns = [];
    if (Array.isArray(props?.columns)) {
      columns.push(...props.columns);
    }
    if (props?.onRowEdit != null || props?.onRowDelete != null) {
      columns.push({
        title: '操作',
        key: 'operations',
        width: props.optionsWidth,
        render: (_dom, row) => getOptions(row)
      });
    }
    return columns;
  }

  return (
    <>
      <TableView>
        <Table
          title={() => {
            return (
              <div className="table-header">
                <Flex className="table-header-title" gap={SPACE} align="center">
                  {props?.title}
                  {selectedRows.length > 0 && (
                    <Tag color="red">{`已选择 ${selectedRows.length} 项`}</Tag>
                  )}
                </Flex>
                <div className="table-header-toolbar">
                  <Flex gap={SPACE}>
                    {props?.toolbar}
                    <Tooltip title="刷新">
                      <ReloadOutlined
                        className={loading ? 'disabled' : ''}
                        onClick={() => {
                          request({ pagination: paginationConfig }, () => {
                            ModalUtil.success('刷新成功');
                          });
                        }}
                      />
                    </Tooltip>
                    {props?.onEdit && (
                      <Tooltip title="编辑">
                        <EditOutlined
                          className={
                            selectedRows.length !== 1
                              ? 'disabled'
                              : props?.editDisabled === true
                                ? 'disabled'
                                : ''
                          }
                          onClick={
                            selectedRows.length !== 1
                              ? undefined
                              : props?.editDisabled === true
                                ? undefined
                                : () => props.onEdit(selectedRows[0])
                          }
                        />
                      </Tooltip>
                    )}
                    {props?.onAdd && (
                      <Tooltip title="新增">
                        <PlusCircleOutlined
                          className={props?.addDisabled === true ? 'disabled' : ''}
                          onClick={props?.addDisabled === true ? undefined : props.onAdd}
                        />
                      </Tooltip>
                    )}
                    {props?.onDelete && (
                      <Tooltip title="删除">
                        <DeleteOutlined
                          className={
                            selectedRows.length < 1
                              ? 'disabled'
                              : props?.deleteDisabled === true
                                ? 'disabled'
                                : ''
                          }
                          disabled
                          onClick={
                            selectedRows.length < 1
                              ? undefined
                              : props?.deleteDisabled === true
                                ? undefined
                                : () => props.onDelete(selectedRows)
                          }
                        />
                      </Tooltip>
                    )}
                  </Flex>
                </div>
              </div>
            );
          }}
          rowKey={props.rowKey}
          bordered={props.bordered}
          dataSource={dataList}
          size={sizeType}
          loading={loading}
          rowSelection={
            props?.rowSelection != null
              ? {
                  ...props?.rowSelection,
                  selectedRowKeys: selectedRows.map((row) => row[props.rowKey]),
                  onChange: (selectedRowKeys, selectedRows, info) => {
                    setSelectedRows(selectedRows);
                    if (props?.rowSelection && props?.rowSelection?.onChange) {
                      props.rowSelection.onChange(selectedRowKeys, selectedRows, info);
                    }
                  }
                }
              : null
          }
          columns={getColumns()}
          pagination={paginationConfig}
          scroll={{ x: props?.scroll?.x ?? 'max-content', y: props?.scroll?.y }}
          onChange={(pagination, filters, sorter) => {
            setPageNo(pagination?.current || 1);
            setPageSize(pagination?.pageSize || LIMIT);
            const options = {
              pagination: pagination,
              filters: filters,
              sorter: sorter
            };
            request(options);
          }}
        >
          {props.children}
          {(props?.onRowEdit != null || props?.onRowDelete != null) && (
            <Table.Column
              title="操作"
              key="operations"
              width={props.optionsWidth}
              render={(_dom, row) => getOptions(row)}
            />
          )}
        </Table>
      </TableView>
    </>
  );
});
